package com.mxf.code.config;


import com.mxf.code.pojo.bo.LoginUser;
import com.mxf.code.util.JwtUtils;
import com.mxf.code.util.RedisUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author : [mxf]
 * @version : [v1.0]
 * @className : JwtAuthenticationTokenFilter
 * @description : [Jwt权限认证过滤器]
 * @createTime : [2022/9/3 21:20]
 * @updateUser : [mxf]
 * @updateTime : [2022/9/3 21:20]
 * @updateRemark : [描述说明本次修改内容]
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取token

        String token = request.getHeader("token");

        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(request, response);
            return;
        }

        // 解析token中的userid

        String userid;

        try {
            Claims claims = JwtUtils.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }

        // 获取缓存中的用户信息,（redis缓存失效）

        String cacheLoginUserInfoKey = "login:" + userid;
        Object unserizlize = RedisUtils.unserizlize((byte[]) redisUtils.get(cacheLoginUserInfoKey));
        LoginUser loginUser = null;
        if (unserizlize instanceof LoginUser) {
            loginUser = (LoginUser) unserizlize;
        }

        if (Objects.isNull(loginUser)) {
            throw new RuntimeException("用户未登录");
        }

        // 存入SecurityContextHolder中，用于后期权限校验
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }
}
